//图片自适应canvas【居中，且无压缩】
export function getImgFixCanvas(canvasW, canvasH, imgW, imgH, scale, offset) {
    if (imgW && imgH && canvasW && canvasH) {
        let cIProp = (imgW / canvasW) / (imgH / canvasH);
        let prop = imgW / imgH;
        let start = []
        let wh = []
        if (cIProp < 1) {
            if (imgH > canvasH) {
                wh = [prop * canvasH, canvasH]
            } else {
                wh = [prop * imgH, imgH]
            }
        } else {
            if (imgW > canvasW) {
                wh = [canvasW, (1 / prop) * canvasW]
            } else {
                wh = [imgW, (1 / prop) * imgW]
            }
        }
        let centerPoint = [canvasW / 2, canvasH / 2]
        wh[0] *= scale[0]
        wh[1] *= scale[1]
        start = [centerPoint[0] - wh[0] / 2 + offset[0], centerPoint[1] - wh[1] / 2 + offset[1]];
        return start.concat(wh);
    } else {
        return [0, 0, 0, 0];
    }
}

//缩放时鼠标偏移量
export function getScaleMouseOffset(centerW, centerH, mouseW, mouseH, nowOffset, position, scale) {
    if (mouseW >= position[0] && mouseW <= position[0] + position[2] && mouseH >= position[1] && mouseH <= position[3]) {
        nowOffset[0] += centerW - mouseW
        nowOffset[1] += centerH - mouseH
        if (position[2] <= centerW * 2) {
            nowOffset[0] = 0
        } else {
            nowOffset[0] = nowOffset[0] > (position[2] / 2 - centerW) ? (position[2] / 2 - centerW) : nowOffset[0]
        }
        if (position[3] <= centerH * 2) {
            nowOffset[1] = 0
        } else {
            nowOffset[1] = nowOffset[1] > (position[3] / 2 - centerH) ? (position[3] / 2 - centerH) : nowOffset[1]
        }
    }

    return nowOffset
}

//通过点位计算点在图像上的原始位置
export function getOriginImgPoint(mouseW, mouseH, position) {
    return [(mouseW - position[0]) / (position[2]), (mouseH - position[1]) / (position[3])];

}

//通过点位原始位置计算现图像上的位置
export function getNowImgPoint(x, y, position) {
    return [(x * position[2]) + position[0], (y * position[3]) + position[1]]
}

//计算线段是否相交
export function hasLineIntersection(a, b, c, d) {
    let max = (t1, t2) => {
        return t1 > t2 ? t1 : t2;
    }
    let min = (t1, t2) => {
        return t1 < t2 ? t1 : t2;
    }
    if (max(c.X, d.X) < min(a.X, b.X) || max(a.X, b.X) < min(c.X, d.X) || max(c.Y, d.Y) < min(a.Y, b.Y) || max(a.Y, b.Y) < min(c.Y, d.Y))
        return 0;
    if (((d.X - a.X) * (d.Y - c.Y) - (d.Y - a.Y) * (d.X - c.X)) * ((d.X - b.X) * (d.Y - c.Y) - (d.Y - b.Y) * (d.X - c.X)) > 0.0000000001)
        return 0;
    if (((c.X - a.X) * (b.Y - a.Y) - (c.Y - a.Y) * (b.X - a.X)) * ((d.X - a.X) * (b.Y - a.Y) - (d.Y - a.Y) * (b.X - a.X)) > 0.0000000001)
        return 0;
    return 1;
}